package com.itheima.my_reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.my_reggie.common.Result;
import com.itheima.my_reggie.pojo.Category;
import com.itheima.my_reggie.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private ICategoryService categoryService;

    //  添加分类的方法
    @PostMapping
    public Result<String> save(@RequestBody Category category) {
//      接收session中的id数据
//        Long empId = (Long) session.getAttribute("emp");
//      统一的设置数据库中非空的字段
//        category.setCreateTime(LocalDateTime.now());
//        category.setUpdateTime(LocalDateTime.now());
//        category.setCreateUser(empId);
//        category.setUpdateUser(empId);
//      调用添加的方法
        categoryService.save(category);
        return Result.success("分类添加成功");
    }

    //  查询分类的数据
    @GetMapping("/page")
    public Result<Page> pageCtg(Integer page, Integer pageSize, String name) {
        Page<Category> pageConfig = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null && name != "", Category::getName, name);
        categoryService.page(pageConfig, wrapper);
        return Result.success(pageConfig);
    }

    //修改分类的状态值
    @PutMapping
    public Result changeCategory(@RequestBody Category category) {
//      从session中获取id的值
//        Long empId = (Long) session.getAttribute("emp");
//      设置更新和修改人的id
//        category.setCreateUser(empId);
//        category.setUpdateUser(empId);
//      调用更新的方法
        categoryService.updateById(category);
        return Result.success(null);
    }

    @DeleteMapping
    public Result<String> deleteById(Long id) {
        categoryService.remove(id);
        return Result.success("分类删除成功");
    }

    @GetMapping("/list")
    public Result queryType(Long type){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType,type);
        List<Category> list = categoryService.list(wrapper);
        return Result.success(list);
    }

}

